package com.example.asyncquery.controller;

import com.example.asyncquery.model.QueryResult;
import com.example.asyncquery.service.QueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/api/query")
@RequiredArgsConstructor
@Slf4j
public class QueryController {

    private final QueryService queryService;

    /**
     * 启动异步查询并立即返回查询ID
     */
    @GetMapping("/start/{id}")
    public ResponseEntity<?> startQuery(@PathVariable Long id) {
        log.info("接收到ID查询请求: {}", id);
        
        // 启动异步查询
        CompletableFuture<QueryResult<?>> future = queryService.queryById(id);
        
        try {
            // 获取初始状态，此时查询可能还在进行中
            QueryResult<?> initialResult = future.get();
            return ResponseEntity.ok(initialResult);
        } catch (InterruptedException | ExecutionException e) {
            log.error("启动查询失败: ", e);
            return ResponseEntity.badRequest().body("查询启动失败: " + e.getMessage());
        }
    }

    /**
     * 获取查询状态和结果
     */
    @GetMapping("/status/{queryId}")
    public ResponseEntity<?> checkQueryStatus(@PathVariable String queryId) {
        log.info("检查查询状态: {}", queryId);
        QueryResult<?> result = queryService.getQueryResult(queryId);
        return ResponseEntity.ok(result);
    }
} 